package com.eric.order.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.eric.api.dto.AccountDto;
import com.eric.api.dto.ProductDto;
import com.eric.api.feign.AccountFeign;
import com.eric.api.feign.ProductFeign;
import com.eric.order.dao.OrderMapper;
import com.eric.order.entity.Order;
import com.eric.order.service.OrderService;
import io.seata.core.context.RootContext;
import io.seata.spring.annotation.GlobalTransactional;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * @author:Eric
 * @date:2021/7/15
 */
@Service
@Slf4j
public class OrderServiceImpl extends ServiceImpl<OrderMapper, Order> implements OrderService {

    @Autowired
    AccountFeign accountFeign;

    @Autowired
    ProductFeign productFeign;

    @GlobalTransactional(name = "tx-group", rollbackFor = Exception.class)
    @Override
    public void create(Order order) {

        log.info("TX-ID : {}", RootContext.getXID());
        //创建订单
        log.info("创建订单");
        this.save(order);
        log.info("创建订单结束");

        //减账户RPC
        log.info("减账户余额");
        accountFeign.reduce(new AccountDto().setId(order.getAccountId()).setAmount(order.getAmount()));
        log.info("减账户余额结束");

        //减库存RPC
        log.info("减商品库存");
        productFeign.reduce(new ProductDto().setId(order.getProductId()).setTotal(order.getTotal()));
        log.info("减商品库存结束");
    }
}
